package http.nio;

import http.nio.thread.SocketChannelThread;
import utils.ThreadPoolUtil;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Set;

public class NioSocketServer {
    private static final int port = 80;

    public static void main(String[] args){
        try {
            ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
            InetSocketAddress address = new InetSocketAddress(port);
            serverSocketChannel.bind(address);
            serverSocketChannel.configureBlocking(false);
            Selector selector = Selector.open();
            serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

            while(true){
                try {
                    selector.select();
                }catch (Exception e){
                    e.printStackTrace();
                }

                Set<SelectionKey> readyKeys = selector.selectedKeys();
                for(SelectionKey readyKey : readyKeys){
                    if(readyKey.isAcceptable()){
                        ServerSocketChannel server = (ServerSocketChannel) readyKey.channel();
                        SocketChannel socketChannel = server.accept();
                        System.out.println("Accept a Connection");
                        ThreadPoolUtil.fixedThreadPool.execute(new SocketChannelThread(socketChannel));
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
